<template>
  <div style="padding: 15px;">
    <div style="margin-bottom: 15px;">
      <Input style="width: 200px;float: left" v-model="searchCourseName" placeholder="请输入课程名称"/>
      <Select style="width: 200px;loat: left" placeholder="请输入开课教师" v-model="addClassesForm.teacherId">
        <Option v-for="item in teacherIdList" :value="item.id" :key="item.id">{{item.staffName}}</Option>
      </Select>
      <Button @click="searchOrg" type="success">搜索</Button>
      <Button @click="add" type="primary" style="float: right;">添加课程</Button>
    </div>
    <Table border ref="selection" :columns="columns" :data="tableData"></Table>
    <page-com :total="total" @page-change="pageChange"></page-com>
    <Modal v-model="addClassesModal" fullscreen :title="modalTitle" @on-ok="submit" @on-cancel="cancel">
      <Form :model="addClassesForm" :label-width="80">
        <Row>
          <Col span="6">
            <FormItem label="课堂名称">
              <Input v-model="addClassesForm.courseName" placeholder="请输入课程名称"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="课程价格">
              <Input v-model="addClassesForm.price" placeholder="请输入课程名称"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="学生人数">
              <Input v-model="addClassesForm.studentNumber" placeholder="请输入学生人数"/>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="课堂等级">
              <Select v-model="addClassesForm.difficulty">
                <Option value="1">初级</Option>
                <Option value="2">中级</Option>
                <Option value="3">高级</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="6">
            <FormItem label="课堂标签">
              <Select v-model="addClassesForm.labelId" multiple>
                <Option v-for="item in labelIdList" :value="item.id" :key="item.id">{{item.labelName}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="机构教师">
              <Select v-model="addClassesForm.teacherId">
                <Option v-for="item in teacherIdList" :value="item.id" :key="item.id">{{item.staffName}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem label="课程封面">
              <div class="demo-upload-list" v-for="item in coverUploadList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="coverRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="uploadq"
                :show-upload-list="false"
                :on-success="coverSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="coverHandleBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="课程背景图">
              <div class="demo-upload-list" v-for="item in bgUploadList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="bgRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="bgSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="bgHandleBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
              <Modal title="查看大图" v-model="visible">
                <img :src="imgName" v-if="visible" style="width: 100%">
              </Modal>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="4">
            <FormItem label="上传网络图片">
              <div class="demo-upload-list" v-for="item in internetList">
                <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="bgRemove(item)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="internetSuccess"
                :format="['jpg','jpeg','png']"
                :before-upload="internetBeforeUpload"
                multiple
                type="drag"
                accept="image/*"
                action="//47.110.52.83:8080/api/picture/upload"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
          <Col span="6"
               v-clipboard:copy="internetPic.join(',')"
               v-clipboard:success="onCopy"
               v-clipboard:error="onError"
          >
            <span v-show="internetPic.length >= 1">{{internetPic.join(',')}}(点我复制)</span>
          </Col>
        </Row>
        <FormItem v-if="flag" label="课程介绍">
          <editor  :dataCon="introduction" :flag="flag"  :catchData="introductionData"/>
        </FormItem>
        <FormItem v-if="flag" label="公告">
          <editor  :dataCon="notice" :flag="flag" :catchData="noticData"/>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="clsdetail" fullscreen title="课程详情">
      <Row type="flex" justify="center">
        <Col span="4">
          <img class="detail-img" :src="details.handcover" alt="">
          <p>课程名称：{{details.courseName}}</p>
          <p>课程价格：{{details.price}}</p>
          <p>所属机构：{{details.orgName}}</p>
          <p>机构教师：{{details.teacherName}}</p>
        </Col>
        <Col span="12">
          <Row>
            <Col span="8">课程章节</Col>
            <Col span="3" offset="13">
              <Button type="primary" @click="addChapter">添加章节</Button>
            </Col>
          </Row>
          <Row class="chapter-layout">
            <Col span="22">
              <Collapse>
                <Panel  v-for="(item, index) in chapterList" :key="index">
                  {{item.chapterName}} {{item.chapterSubtitle}}
                  <Button size="small" @click="addSection(item)" type="warning">添加小节</Button>
                  <Button size="small" @click="editorChapter(item)" type="primary">编辑</Button>
                  <Button size="small" @click="chapterdelete(item.id)" type="error">删除</Button>
                  <div slot="content">
                    <p v-for="(items, index) in item.genseesList" :key="index">
                      {{items.genseeTitle}}
                      <Button style="text-align: right" size="small" @click="editSection(items)" type="primary">编辑</Button>
                      <Button style="text-align: right" size="small" @click="deleteSection(items)" type="error">删除</Button>
                    </p>
                  </div>
                </Panel>
              </Collapse>
            </Col>
          </Row>
        </Col>
      </Row>
      <Modal :title="chapterTitle" v-model="chapterShow" :mask-closable="false" @on-ok="chapterSubmit" @on-cancel="chaptercancel">
        <Form :label-width="80">
          <FormItem label="章节名称">
            <Input v-model="chapterName" placeholder="请输入章节名称" />
          </FormItem>
          <FormItem label="章节副标题">
            <Input v-model="chapterSubtitle" placeholder="请输入章节副标题" />
          </FormItem>
        </Form>
      </Modal>
      <Modal :title="sectioneTitle" v-model="sectioneShow" :mask-closable="false" @on-ok="sectioneSubmit" @on-cancel="sectionecancel">
        <Form :label-width="80">
          <FormItem label="小节名称">
            <Input v-model="subject" placeholder="请输入小节名称" />
          </FormItem>
          <FormItem label="开课时间">
            <DatePicker :value="startDate" @on-change="sectioneTime" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开课时间"></DatePicker>
          </FormItem>
        </Form>
      </Modal>
    </Modal>
  </div>
</template>

<script>
  import Editor from '@/components/editor'
  import PageCom from '@/components/page'
  import {formatDate} from '_com/date'
  export default {
    components: {
      Editor,
      PageCom
    },
    data () {
      return {
        sectioneTitle: '',
        sectioneShow: false,
        subject: '',
        startDate: '',
        chapterTitle: '',
        chapterName: '',
        chapterSubtitle: '',
        chapterShow: false,
        addClassesForm: {
          labelId: [],
          orgId: [],
          teacherId: []
        },
        details: {},
        flag: false,
        setUp: false,
        clsdetail: false,
        columns: [
          {
            title: '课程名称',
            key: 'courseName',
            align: 'center'
          },
          {
            title: '课程难度',
            key: 'userName',
            align: 'center',
            render: (h, params) => {
              const row = params.row
              const text = row.difficulty === '1' ? '初级' : row.difficulty === '2' ? '中级' : '高级'
              return h('div', text)
            }
          },
          {
            title: '所属机构',
            key: 'orgName',
            align: 'center'
          },
          {
            title: '所属教师',
            key: 'teacherName',
            align: 'center'
          },
          {
            title: '课程价格（元）',
            key: 'price',
            align: 'center'
          },
          {
            title: '课程标签',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('p', params.row.labelNames.join(','))
              ])
            }
          },
          {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.details = params.row
                      this.searchChapter(params.row.id)
                      this.clsdetail = true
                    }
                  }
                }, '课程详情'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editor()
                      let row = params.row
                      this.introduction = row.introduction
                      this.notice = row.notice
                      this.addClassesForm.courseName = row.courseName
                      this.addClassesForm.price = row.price
                      this.addClassesForm.studentNumber = row.studentNumber
                      this.addClassesForm.difficulty = row.difficulty
                      this.addClassesForm.labelId = row.labelIds
                      this.addClassesForm.teacherId = row.teacherId
                      this.coverUploadList = [{url: row.handcover, status: 'finished'}]
                      this.bgUploadList = [{url: row.bgImage, status: 'finished'}]
                      this.bgPic = row.bgImage
                      this.coverPic = row.handcover
                      this.id = row.id
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '你确定要删除吗？',
                        okText: '确定',
                        cancelText: '取消',
                        onOk: () => {
                          this.remove(params.row.id)
                        }
                      })
                    }
                  }
                }, '删除')
              ])
            }
          }
        ],
        tableData: [],
        size: 10,
        number: 0,
        total: 0,
        searchCourseName: '',
        searchTeacherId: [],
        searchOrgId: [],
        areaModel: '',
        addClassesModal: false,
        modalTitle: '',
        orgBatchAddStudentModal: false,
        content: '',
        imgName: '',
        visible: false,
        bgPic: '',
        bgUploadList: [],
        coverPic: '',
        coverUploadList: [],
        internetPic: [],
        internetList: [],
        labelIdList: [],
        orgIdList: [],
        teacherIdList: [],
        notice: '',
        introduction: '',
        uptoken: {},
        orgId: '',
        chapterList: [],
        chapterId: '',
        sectioneItem: ''
      }
    },
    mounted () {
      this.coursePage()
      this.labelList()
      this.teacherList()
    },
    methods: {
      coursePage() {
        this.$get('/api/api/org/course/page', {
          courseName: this.searchCourseName,
          teacherId: this.searchTeacherId,
          courseType: 1,
          liveType: 2,
          size: this.size,
          number: this.number
        }).then((res) => {
          this.total = res.total
          this.tableData = res.data
        })
      },
      pageChange(data) {
        this.number = data
      },
      labelList() {
        this.$get('/api/api/admin/label/list', {labelCategory: '3'}).then((res) => {
          if (res.code === 0) {
            this.labelIdList = res.data
          }
        })
      },
      teacherList() {
        this.$get('/api/api/org/admin/teacher/list').then((res) => {
          if (res.code === 0) {
            this.teacherIdList = res.data
          }
        })
      },
      orgIdChange(change) {
        this.orgId = change
        this.teacherList()
      },
      title(title) {
        this.modalTitle = title
        this.addClassesModal = true
      },
      add() {
        this.flag = true
        this.title('添加课程')
      },
      editor() {
        this.flag = true
        this.title('编辑课程')
      },
      submit() {
        if (this.modalTitle === '添加课程') {
          this.addOrg()
        } else {
          this.theEditor()
        }
      },
      addOrg() {
        let form = {
          bgImage: this.bgPic,
          courseName: this.addClassesForm.courseName,
          difficulty: this.addClassesForm.difficulty,
          handcover: this.coverPic,
          introduction: this.introduction,
          labelId: this.addClassesForm.labelId,
          notice: this.notice,
          courseType: 1,
          liveType: 2,
          price: this.addClassesForm.price,
          studentNumber: this.addClassesForm.studentNumber,
          teacherId: this.addClassesForm.teacherId
        }
        this.$post('/api/api/org/course/add', form).then((res) => {
          if (res.code === 0) {
            this.$Message.success('添加成功')
            this.cancel()
            this.coursePage()
          } else {
            this.$Message.success('添加失败')
          }
        }).catch((rel) => {
          this.$Message.success('添加失败')
        })
      },
      theEditor() {
        let form = {
          bgImage: this.bgPic,
          courseName: this.addClassesForm.courseName,
          difficulty: this.addClassesForm.difficulty,
          handcover: this.coverPic,
          introduction: this.introduction,
          labelId: this.addClassesForm.labelId,
          notice: this.notice,
          price: this.addClassesForm.price,
          studentNumber: this.addClassesForm.studentNumber,
          teacherId: this.addClassesForm.teacherId,
          id: this.id
        }
        this.$put('/api/api/org/course/update', form).then((res) => {
          if (res.code === 0) {
            this.$Message.success('编辑成功')
            this.cancel()
            this.coursePage()
          } else {
            this.$Message.success('编辑失败')
          }
        }).catch((rel) => {
          this.$Message.success('编辑失败')
        })
      },
      remove(id) {
        this.$deletes('/api/api/admin/course/delete', {id: id}).then((res) => {
          if (res.code === 0) {
            this.$Message.success('删除成功')
            this.coursePage()
          } else {
            this.$Message.success('删除失败')
          }
        }).catch((rel) => {
          this.$Message.success('删除失败')
        })
      },
      searchOrg() {
        this.coursePage()
      },
      cancel() {
        this.flag = false
        this.bgPic = ''
        this.addClassesForm.courseName = ''
        this.addClassesForm.difficulty = ''
        this.coverPic = ''
        this.introduction = ''
        this.addClassesForm.labelId = []
        this.notice = ''
        this.addClassesForm.orgId = []
        this.addClassesForm.price = ''
        this.addClassesForm.studentNumber = ''
        this.addClassesForm.teacherId = []
        this.bgUploadList = []
        this.coverUploadList = []
      },
      introductionData(value) {
        this.introduction = value
      },
      noticData(value) {
        this.notice = value
      },
      handleView (url) {
        this.imgName = url
        this.visible = true
      },
      coverRemove (file) {
        let url = '/api/api/picture/delete'
        let fileUrl = {
          fileUrl: file.url
        }
        this.$deletes(url, fileUrl).then((res) => {
          if (res.message) {
            this.coverPic.splice(this.pic.indexOf(file), 1)
            this.coverUploadList.splice(this.coverUploadList.indexOf(file), 1)
            this.$Message.success('删除成功')
          } else {
            this.$Message.error('删除失败')
          }
        })
      },
      bgRemove (file) {
        let url = '/api/api/picture/delete'
        let fileUrl = {
          fileUrl: file.url
        }
        this.$deletes(url, fileUrl).then((res) => {
          if (res.message) {
            this.bgPic.splice(this.pic.indexOf(file), 1)
            this.bgUploadList.splice(this.bgUploadList.indexOf(file), 1)
            this.$Message.success('删除成功')
          } else {
            this.$Message.error('删除失败')
          }
        })
      },
      coverSuccess(res, file) {
        file.url = file.response.data
        this.$Message.success('上传成功')
        this.coverPic = file.response.data
        this.coverUploadList.push(file)
      },
      bgSuccess(res, file) {
        file.url = file.response.data
        this.$Message.success('上传成功')
        this.bgPic = file.response.data
        this.bgUploadList.push(file)
      },
      bgHandleBeforeUpload () {
        const check = this.bgUploadList.length < 1
        if (!check) {
          this.$Message.error('最多上传1张图片')
        }
        return check
      },
      coverHandleBeforeUpload() {
        const check = this.coverUploadList.length < 1
        if (!check) {
          this.$Message.error('最多上传1张图片')
        }
        return check
      },
      internetBeforeUpload() {
        this.internetPic = []
        this.internetList = []
        const check = this.internetList.length < 1
        if (!check) {
          this.$Message.error('最多上传1张图片')
        }
        return check
      },
      internetSuccess(res, file) {
        file.url = file.response.data
        this.$Message.success('上传成功')
        this.internetPic.push(file.response.data)
        this.internetList.push(file)
      },
      onCopy(e) {
        this.$Message.success('复制成功')
      },
      onError(e) {
        this.$Message.error('复制失败')
      },
      addChapter() {
        this.chapterTitle = '添加章节'
        this.chapterShow = true
      },
      editorChapter(item) {
        this.chapterTitle = '编辑章节'
        this.chapterName = item.chapterName
        this.chapterSubtitle = item.chapterSubtitle
        this.chapterId = item.id
        this.chapterShow = true
      },
      searchChapter(id) {
        this.$get('/api/api/teacher/chapters/list', {id: id}).then((res) => {
          if (res.code === 0) {
            this.chapterList = res.data
          }
        })
      },
      chapterSubmit() {
        if (this.chapterTitle === '添加章节') {
          this.$post('/api/api/teacher/chapters/add', {
            chapterName: this.chapterName,
            chapterSubtitle: this.chapterSubtitle,
            courseId: this.details.id
          }).then((res) => {
            if (res.code === 0) {
              this.$Message.success('添加成功')
              this.searchChapter(this.details.id)
              this.chaptercancel()
            } else {
              this.$Message.error('添加失败')
            }
          }).catch((res) => {
            this.$Message.error('添加失败')
          })
        } else {
          this.$put('/api/api/teacher/chapters/update', {
            chapterName: this.chapterName,
            chapterSubtitle: this.chapterSubtitle,
            id: this.chapterId
          }).then((res) => {
            if (res.code === 0) {
              this.$Message.success('修改成功')
              this.searchChapter(this.details.id)
              this.chaptercancel()
            } else {
              this.$Message.error('修改失败')
            }
          }).catch((res) => {
            this.$Message.error('修改失败')
          })
        }
      },
      chapterdelete(id) {
        this.$Modal.confirm({
          title: '你确定要删除吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.$deletes('/api/api/teacher/chapters/delete', {
              id: id
            }).then((res) => {
              if (res.code === 0) {
                this.$Message.success('删除成功')
                this.searchChapter(this.details.id)
              } else {
                this.$Message.error('删除失败')
              }
            }).catch((res) => {
              this.$Message.error('删除失败')
            })
          }
        })
      },
      chaptercancel() {
        this.chapterName = ''
        this.chapterSubtitle = ''
        this.chapterId = ''
      },
      addSection(item) {
        this.sectioneTitle = '添加小节'
        this.sectioneItem = item
        this.sectioneShow = true
      },
      editSection(items) {
        let data = Number(items.startDate)
        this.sectioneTitle = '编辑小节'
        this.sectioneItem = items
        this.subject = items.genseeTitle
        this.startDate = formatDate(new Date(data), 'yyyy-MM-dd hh:mm')
        this.sectioneShow = true
      },
      sectioneTime(e) {
        this.startDate = e
      },
      sectioneSubmit() {
        if (this.sectioneTitle === '添加小节') {
          this.$post('/api/creatRoom', {
            startDate: new Date(this.startDate).getTime(),
            subject: this.subject,
            sysCourseId: this.sectioneItem.courseId,
            chapterId: this.sectioneItem.id
          }).then((res) => {
            if (res.code === 0) {
              this.$Message.success('添加成功')
              this.searchChapter(this.details.id)
              this.sectionecancel()
            } else {
              this.$Message.success('添加失败')
            }
          }).catch((res) => {
            this.$Message.success('添加失败')
          })
        } else {
          this.$post('/api/modifyRoomUrl', {
            startDate: new Date(this.startDate).getTime(),
            subject: this.subject,
            id: this.sectioneItem.id
          }).then((res) => {
            if (res.code === 0) {
              if (res.data === '第三方修改失败，请稍后再试！') {
                this.$Message.success(res.data)
                return false
              }
              this.$Message.success('修改成功')
              this.searchChapter(this.details.id)
              this.sectionecancel()
            } else {
              this.$Message.success('修改失败')
            }
          }).catch((res) => {
            this.$Message.success('修改失败')
          })
        }
      },
      deleteSection(items) {
        this.$get('/api/deleteRoomUrl', {
          roomid: items.id
        }).then((res) => {
          if (res.code === 0) {
            this.$Message.success('删除成功')
            this.searchChapter(this.details.id)
          } else {
            this.$Message.success('删除失败')
          }
        }).catch((res) => {
          this.$Message.success('删除失败')
        })
      },
      sectionecancel() {
        this.startDate = ''
        this.subject = ''
        this.sectioneItem = ''
      }
    }
  }
</script>

<style scoped>
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .detail-img{
    width: 260px;
    height: 160px;
  }
  .chapter-layout{
    margin-top: 20px;
  }
</style>

